package com.cswangdao.utils;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.cswangdao.result.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class ResponseMineUtil {

    static JSONConfig jsonConfig = new JSONConfig();
    static {
        jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    public static <T> void success(HttpServletResponse response,T data){

        Result<T> success = Result.success(data);

        String jsonStr = JSONUtil.toJsonStr(success,jsonConfig);
        try {
            response.getWriter().println(jsonStr);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static <T> void success(HttpServletResponse response){
        Result<T> success = Result.success();
        String jsonStr = JSONUtil.toJsonStr(success,jsonConfig);
        try {
            response.getWriter().println(jsonStr);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static  void error(HttpServletResponse response,String msg){
        Result<String> error = Result.error(msg);
        String jsonStr = JSONUtil.toJsonStr(error,jsonConfig);
        try {
            response.getWriter().println(jsonStr);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static  void error(HttpServletResponse response){
        Result<String> error = Result.error();
        String jsonStr = JSONUtil.toJsonStr(error,jsonConfig);
        try {
            response.getWriter().println(jsonStr);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
